package com.cloud.common.configure;

import cn.hutool.core.convert.Convert;
import com.alibaba.ttl.TransmittableThreadLocal;
import com.cloud.common.constants.GlobalConstants;
import com.cloud.domain.LoginUser;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 全局上下文工具类
 * 获取当前线程变量中的 用户id、用户名称、Token等信息
 * 注意：必须在网关通过请求头的方法传入，同时在请求拦截器设置值。
 *
 * @author yzj
 */
public class TransmittableHolder {

    private static final TransmittableThreadLocal<Map<String, Object>> THREAD_LOCAL = new TransmittableThreadLocal<>();

    public static void set(String key, Object value) {
        Map<String, Object> map = getLocalMap();
        map.put(key, value == null ? "" : value);
    }

    public static String get(String key) {
        Map<String, Object> map = getLocalMap();
        return Convert.toStr(map.getOrDefault(key, ""));
    }

    public static <T> T get(String key, Class<T> clazz) {
        Map<String, Object> map = getLocalMap();
        return (T) map.getOrDefault(key, null);
    }

    public static Map<String, Object> getLocalMap() {
        Map<String, Object> map = THREAD_LOCAL.get();
        if (map == null) {
            map = new ConcurrentHashMap<>();
            THREAD_LOCAL.set(map);
        }
        return map;
    }

    public static void setLocalMap(Map<String, Object> threadLocalMap) {
        THREAD_LOCAL.set(threadLocalMap);
    }

    public static Long getUserId() {
        return Convert.toLong(get(GlobalConstants.userId), 0L);
    }

    public static void setUserId(String userId) {
        set(GlobalConstants.userId, userId);
    }

    public static String getUserName() {
        return get(GlobalConstants.userName);
    }

    public static void setUserName(String userName) {
        set(GlobalConstants.userName, userName);
    }

    public static Long getDeptId() {
        return Convert.toLong(get(GlobalConstants.deptId));
    }

    public static void setDeptId(String deptId) {
        set(GlobalConstants.deptId, deptId);
    }

    public static String getTokenKey() {
        return get(GlobalConstants.tokenKey);
    }

    public static void setTokenKey(String tokenKey) {
        set(GlobalConstants.tokenKey, tokenKey);
    }

    public static LoginUser getLoginUser() {
        return get(GlobalConstants.loginUser, LoginUser.class);
    }

    public static void setLoginUser(LoginUser loginUser) {
        set(GlobalConstants.loginUser, loginUser);
    }

    public static void remove() {
        THREAD_LOCAL.remove();
    }

}
